package service

import (
	"fmt"
	"ims/app/dao"
	"ims/tools"
	"ims/tools/response"
	"strings"
	"time"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
)

//访客用户 接入时验证 token
func MiddlewareUserToken(r *ghttp.Request) {
	author := r.GetHeader("Authori-zation")
	if author == "" {
		response.JsonResponse(r, g.Map{
			"status": 200,
			"msg":    "缺少token",
		})
	}
	token := gstr.Split(author, " ")[1]
	appInfo := dao.ChatApplication.ParseToken(token)
	if appInfo.Id > 0 {
		r.SetParam("appId", appInfo.Appid)
		r.SetParam("appInfo", appInfo)
		//g.Log().Debug("==========iv:", appInfo)
		//g.Log().Debug(tools.Encrypter.BearEncode("我是个好人"))
		//g.Log().Debug(tools.Encrypter.BearDecrypt("eyJpdiI6Ik1EZURuS1VyRFF6Zm12VnNUSm5vMUE9PSIsIm1hYyI6ImViSEwzYjFVdXVTd2I3YnhZMG1nNDQrRU5HdXFUbVoxVlNCMXp4UGtMZXc9IiwidmFsdWUiOiJnQ0s1VVZ0YTh1NmQzcTdLY3NFdU53PT0ifQ==", false))
		r.Middleware.Next()
	} else {
		response.JsonResponse(r, g.Map{
			"status": 404,
			"msg":    "token错误",
		})
	}

}

//新版
func MiddlewareCORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}

//新版webapi包，验证api头部里面带有的token 获取 kefu 账号信息
func KefuAuthTokenMiddleware(r *ghttp.Request) {
	author := r.GetHeader("Authori-zation")
	if author == "" {
		response.JsonResponse(r, g.Map{
			"status": 200,
			"msg":    "缺少token",
		})
	}
	g.Log().Debug(author)
	token := gstr.Split(author, " ")[1]

	userinfo, valid := tools.JwtParseToken(token)
	if valid != nil {
		response.JsonResponse(r, g.Map{
			"status": 200,
			"msg":    "token不正确1",
		})
	}
	g.Log().Debug("KefuAuthTokenMiddleware:{}", userinfo)
	// map[id:11 type:kefu]
	if userinfo == nil {
		response.JsonResponse(r, g.Map{
			"status": 200,
			"msg":    "token不正确2",
		})
	}
	jti := gconv.Map(userinfo["jti"])
	//把kefuInfo 传递给 next 可以直接获取
	//r.SetParam("kefuInfo", info)
	r.SetParam("kefuId", jti["id"])
	r.Middleware.Next()

}

//下面是旧版的 不要了=====================
//验证 check_auth 的token登陆信息
func JWTauthMiddewareAuth(r *ghttp.Request) {

	token := r.GetHeader("token")

	if token == "" {
		token = r.GetQueryString("token")
	}
	userinfo := tools.ParseToken(token)
	if userinfo == nil || userinfo["name"] == nil || userinfo["create_time"] == nil {
		response.JsonResponse(r, g.Map{
			"code": 400,
			"msg":  "验证失败",
		})

	}
	createTime := int64(userinfo["create_time"].(float64))
	var expire int64 = 24 * 60 * 60
	nowTime := time.Now().Unix()
	if (nowTime - createTime) >= expire {
		response.JsonResponse(r, g.Map{
			"code": 401,
			"msg":  "token失效",
		})

	}
	r.SetParam("user", userinfo["name"])
	g.Log().Debug(userinfo)
	//if userinfo["type"]=="kefu"{
	r.SetParam("kefu_id", userinfo["kefu_id"])
	r.SetParam("kefu_name", userinfo["name"])
	r.SetParam("role_id", userinfo["role_id"])
	//}
	r.Middleware.Next()
}

//验证某个roleId 的url路径访问是否被允许
func MiddlewareRbacAuth(r *ghttp.Request) {

	roleId := r.Get("role_id", "0")
	role := dao.FindRole(gconv.String(roleId))
	var flag bool
	rPaths := strings.Split(r.Request.RequestURI, "?")
	uriParam := fmt.Sprintf("%s:%s", r.Request.Method, rPaths[0])
	if role.Method != "*" || role.Path != "*" {
		paths := strings.Split(role.Path, ",")
		for _, p := range paths {
			if uriParam == p {
				flag = true
				break
			}
		}
		if !flag {
			response.JsonResponse(r, g.Map{
				"code": 403,
				"msg":  "没有权限:" + uriParam,
			})

			return
		}

	}
	r.Middleware.Next()
}
